﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;

namespace JY.Label.Test
{
    /// <summary>
    /// LabelaryApi接口调用
    /// </summary>
    public static class LabelaryApiService
    {
        #region # 生成标签图片——BitmapImage GenerateLabelImage(string zplLabelCommand, int dpmm, double width, double height)
        /// <summary>
        /// 生成标签图片
        /// </summary>
        /// <param name="zplLabelCommand">ZPL命令</param>
        /// <param name="dpmm"></param>
        /// <param name="width"></param>
        /// <param name="height"></param>
        public static BitmapImage GenerateLabelImage(string zplLabelCommand, int dpmm, double width, double height)
        {
            int index = 0;
            string uri = $"http://api.labelary.com/v1/printers/{dpmm}dpmm/labels/{width}x{height}/{index}/";
            byte[] zplBuffer = Encoding.UTF8.GetBytes(zplLabelCommand);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = "POST";
            request.Accept = "image/png"; //application/pdf, omit this line to get PNG images back,
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = zplBuffer.Length;

            Stream requestStream = request.GetRequestStream();
            requestStream.Write(zplBuffer, 0, zplBuffer.Length);
            requestStream.Close();

            BitmapImage bitmapImage = new BitmapImage();
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream responseStream = response.GetResponseStream();
                MemoryStream outstream = new MemoryStream();
                const int bufferLen = 4096;
                byte[] buffer = new byte[bufferLen];
                int count = 0;
                while ((count = responseStream.Read(buffer, 0, bufferLen)) > 0)
                {
                    outstream.Write(buffer, 0, count);
                }
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = outstream;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad; 
                bitmapImage.EndInit();
                outstream.Dispose();
            }
            catch (WebException e)
            {
                Console.WriteLine($"LabelaryApi接口调用生成图片失败: {e.Message}");
            }

            return bitmapImage;
        } 
        #endregion
    }
}
